package chapter6.meine.exercises;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JApplet;
import javax.swing.JPanel;

public class DragTwoObjectsApplet extends JApplet {
	public void init() {
		setContentPane(new DragTwoObjects());
	}// end of init()

	public class DragTwoObjects extends JPanel{
		private int yCorRed, yCorBlue;
		private int xCorRed;
		private int xCorBlue;
	

		public DragTwoObjects() {
			
			xCorBlue = 10;
			yCorBlue = 10;
			xCorRed = 50;
			yCorRed = 10;
			setBackground(Color.lightGray);
			
			DragListener listener = new DragListener();
					
			addMouseListener(listener);
			addMouseMotionListener(listener);

		}// end of constructor DragTwoObjects()

		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.setColor(Color.RED);
			g.fillRect(xCorRed, yCorRed, 30, 30);

			g.setColor(Color.BLUE);
			g.fillRect(xCorBlue, yCorBlue, 30, 30);

		}//end of paintComponent()
		
		public class DragListener implements MouseListener, MouseMotionListener {
			 int xOffset, yOffset;
			 boolean isBlueDragged, dragging;


			@Override
			public void mousePressed(MouseEvent e) {
				if (dragging)
					return;
				int x = e.getX();
				int y = e.getY();
				if (x >= xCorBlue && x <= (xCorBlue + 30) && y >= yCorBlue
						&& y <= (yCorBlue + 30)) {
					isBlueDragged = true;
					dragging = true;
					xOffset = xCorBlue - x;
					yOffset = yCorBlue - y;

				} else if (x >= xCorRed && x <= (xCorRed + 30)
						&& y >= yCorRed && y <= (yCorRed + 30)) {
					isBlueDragged = false;
					dragging = true;
					xOffset = xCorRed - x;
					yOffset = yCorRed - y;
				}

			}

			@Override
			public void mouseReleased(MouseEvent e) {
				dragging = false;

			}

			@Override
			public void mouseDragged(MouseEvent e) {
				if (dragging == false)
					return;
				int x = e.getX();
				int y = e.getY();
				if (isBlueDragged) {

					xCorBlue = x + xOffset;
					yCorBlue = y + yOffset;

				} else {

					xCorRed = x + xOffset;
					yCorRed = y + yOffset;

				}
				repaint();

			}
			@Override
			public void mouseClicked(MouseEvent e) {}

			@Override
			public void mouseEntered(MouseEvent e) {}

			@Override
			public void mouseExited(MouseEvent e) {}

			@Override
			public void mouseMoved(MouseEvent e) {}
		}// end of class DragListener



	}// end of class DragTwoObjects
}// end of class DragTwoObjectsApplet